import random
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use('TkAgg')
_x = [x/100 for x in range(100)]
_y = [3*x + 10 + random.random() for x in _x]
# 初始化参数
w = random.random()
b = random.random()
# 初始化学习率
learn_rate = 0.1

for i in range(1000):
  for x ,y in zip(_x,_y):
    # 模型
    # 1前向传播
    y_pred = w * x + b

    loss =(y_pred-y) ** 2
    # wi+1 = wi - learn_rate * dw
    dw = 2 * (y_pred - y) * x
    db = 2 * (y_pred - y)
    # 更新参数
    w = w - learn_rate * dw
    b = b - learn_rate * db

    plt.ion()
    plt.cla()
    plt.scatter(_x, _y)
    plt.plot(_x, [w * x + b for x in _x])
    plt.pause(0.01)
  plt.show()
